package com.nowcoder.code.lcof;

import com.algorithm.model.ListNode;

public class JZ25 {

    public ListNode Merge(ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null) {
            return pHead2;
        }
        if (pHead2 == null) {
            return pHead1;
        }
        ListNode head;
        ListNode res;
        if (pHead1.val > pHead2.val) {
            head = pHead2;
            pHead2 = pHead2.next;
        } else {
            head = pHead1;
            pHead1 = pHead1.next;
        }
        res = head;

        while (pHead1 != null && pHead2 != null) {
            if (pHead1.val > pHead2.val) {
                head.next = pHead2;
                pHead2 = pHead2.next;
            } else {
                head.next = pHead1;
                pHead1 = pHead1.next;
            }
            head = head.next;
        }

        if (pHead1 != null) {
            head.next = pHead1;
        }
        if (pHead2 != null) {
            head.next = pHead2;
        }

        return res;

    }

}
